/* **
* 校验token的中间件
*/
const jwt = require('jsonwebtoken')
const {key} = require('../config')
const {
  ThrowError,
  TokenError,
  AuthError
} = require('../core/error')

function m(type=1){
  return async (ctx, next) => {
    // 从header中或query中获取携带的token
    let token = ctx.request.header.token || ctx.request.query.token
    if(!token){
      throw new TokenError()
    }
    try {
      let decode = jwt.verify(token, key)
      ctx.auth = {
        uid: decode.uid,
        type: decode.type
      }
    } catch (error) {
      throw new TokenError()
    }

    if(type > ctx.auth.type){
      throw new AuthError()
    }

    await next()
  }
}


module.exports = m